<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { pinyin } from 'pinyin-pro'
import ShortcutItem from './ShortcutItem.vue'
import type { Shortcut } from '../types';

interface Props {
  shortcuts: Shortcut[];
  searchQuery: string;
}

interface Emits {
  (e: 'launchShortcut', shortcut: Shortcut): void;
  (e: 'refreshShortcuts'): void;
  (e: 'hideToTray'): void;
  (e: 'blurSearch'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const selectedIndex = ref(0);
const launchingIndex = ref(-1); // 正在启动的应用索引


/**
 * 搜索匹配函数
 * 支持直接字符串匹配、拼音全拼匹配、拼音首字母匹配
 * @param shortcutName 快捷方式名称
 * @param query 搜索查询字符串
 * @returns 是否匹配
 */
function isSearchMatch(shortcutName: string, query: string): boolean {
  const lowerQuery = query.toLowerCase().trim();
  const lowerName = shortcutName.toLowerCase();
  
  // 1. 直接匹配中文名称
  if (lowerName.includes(lowerQuery)) {
    return true;
  }
  
  // 2. 拼音全拼匹配
   try {
     const fullPinyin = pinyin(shortcutName, { toneType: 'none', type: 'array' }).join('');
     if (fullPinyin.toLowerCase().includes(lowerQuery)) {
       return true;
     }
     
     // 3. 拼音首字母匹配
     const firstLetters = pinyin(shortcutName, { pattern: 'first', toneType: 'none', type: 'array' }).join('');
     if (firstLetters.toLowerCase().includes(lowerQuery)) {
       return true;
     }

    
  } catch (error) {
     console.warn('[WARN] 拼音转换失败:', error);
     return false;
   }
  
  return false;
}

// 搜索过滤计算属性
const filteredShortcuts = computed(() => {
  if (!props.searchQuery.trim()) {
    return props.shortcuts;
  }
  
  const results = props.shortcuts.filter(shortcut => isSearchMatch(shortcut.name, props.searchQuery));
  
  return results;
});

// 监听搜索查询变化，重置选中索引
const resetSelectedIndex = () => {
  selectedIndex.value = 0;
};

// 计算网格列数
function getGridColumns(): number {
  const gridElement = document.querySelector('.shortcuts-grid');
  if (!gridElement) return 6; // 默认列数
  
  // 计算实际列数
  const containerWidth = gridElement.clientWidth;
  const minItemWidth = 90; // minmax(90px, 1fr) 中的最小宽度
  const gap = 16; // gap: 16px
  const padding = 48; // padding: 0 24px (左右各24px)
  
  const availableWidth = containerWidth - padding;
  const columns = Math.floor((availableWidth + gap) / (minItemWidth + gap));
  
  return Math.max(1, columns);
}

/**
 * 自动滚动到选中项目
 * 确保选中的快捷方式图标在可视区域内
 */
function scrollToSelectedItem() {
  nextTick(() => {
    const selectedElement = document.querySelector('.shortcut-item.selected');
    if (selectedElement) {
      // 使用更简单直接的滚动方式，确保能滚动到边界
      selectedElement.scrollIntoView({
        behavior: 'smooth',
        block: 'center',
        inline: 'nearest'
      });
    }
  });
}

// 监听selectedIndex变化，自动滚动
watch(selectedIndex, () => {
  scrollToSelectedItem();
});

// 键盘事件处理
function handleKeydown(event: KeyboardEvent) {
  if (filteredShortcuts.value.length === 0) return;
  
  // 如果焦点在搜索框上，只处理方向键和回车键
  const isSearchFocused = document.activeElement?.tagName === 'INPUT';
  
  const totalItems = filteredShortcuts.value.length;
  const columns = getGridColumns();
  const currentRow = Math.floor(selectedIndex.value / columns);
  const currentCol = selectedIndex.value % columns;
  
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault();
      const nextRowIndex = selectedIndex.value + columns; 
      // 只有当下一行存在时才移动，避免跳转到最后一个元素
      if (nextRowIndex < totalItems) {
        selectedIndex.value = nextRowIndex;
      }
      if (isSearchFocused) {
        emit('blurSearch');
      }
      break;
      
    case 'ArrowUp':
      event.preventDefault();
      const prevRowIndex = selectedIndex.value - columns;
      // 只有当上一行存在时才移动，避免跳转到第一个元素
      if (prevRowIndex >= 0) {
        selectedIndex.value = prevRowIndex;
      }
      if (isSearchFocused) {
        emit('blurSearch');
      }
      break;
      
    case 'ArrowRight':
      event.preventDefault();
      if (currentCol < columns - 1 && selectedIndex.value < totalItems - 1) {
        selectedIndex.value = selectedIndex.value + 1;
      } else if (currentCol === columns - 1 && selectedIndex.value + columns - currentCol < totalItems) {
        // 如果在行末，跳到下一行的开头
        selectedIndex.value = selectedIndex.value + columns - currentCol;
      }
      if (isSearchFocused) {
        emit('blurSearch');
      }
      break;
      
    case 'ArrowLeft':
      event.preventDefault();
      if (currentCol > 0) {
        selectedIndex.value = selectedIndex.value - 1;
      } else if (currentCol === 0 && currentRow > 0) {
        // 如果在行首，跳到上一行的末尾
        const prevRowLastIndex = Math.min((currentRow - 1) * columns + columns - 1, totalItems - 1);
        selectedIndex.value = prevRowLastIndex;
      }
      if (isSearchFocused) {
        emit('blurSearch');
      }
      break;
      
    case 'Enter':
      event.preventDefault();
      if (filteredShortcuts.value[selectedIndex.value]) {
        launchApp(selectedIndex.value);
      }
      break;
      
    case 'Escape':
      event.preventDefault();
      emit('hideToTray');
      break;
  }
}

/**
 * 启动应用程序
 * @param index 应用索引
 */
function launchApp(index: number) {
  if (launchingIndex.value !== -1) return; // 防止重复启动
  
  launchingIndex.value = index;
  
  // 显示启动动画，延迟一下再实际启动应用
  setTimeout(() => {
    emit('launchShortcut', filteredShortcuts.value[index]);
    
    // 启动后延迟重置动画状态
    setTimeout(() => {
      launchingIndex.value = -1;
    }, 500);
  }, 100);
}

// 处理快捷方式点击
function handleShortcutClick(index: number) {
  selectedIndex.value = index;
  launchApp(index);
}

// 处理快捷方式双击
function handleShortcutDoubleClick(index: number) {
  launchApp(index);
}

// 暴露重置选中索引的方法
defineExpose({
  resetSelectedIndex
});

onMounted(() => {
  document.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
});
</script>

<template>
  <div class="shortcuts-container">
    <div class="shortcuts-grid">
        <ShortcutItem
          v-for="(shortcut, index) in filteredShortcuts" 
          :key="`${shortcut.path}-${index}`"
          :shortcut="shortcut"
          :is-selected="index === selectedIndex"
          :is-launching="index === launchingIndex"
          @click="handleShortcutClick(index)"
          @double-click="handleShortcutDoubleClick(index)"
        />
      </div>
  </div>     
</template>

<style lang="scss" scoped>

.shortcuts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
  gap: 16px;
  padding: 16px 24px;
  justify-items: center;
}

/* 图标渲染优化样式 - 应用到所有shortcuts-grid */
.shortcuts-grid,
.shortcuts-grid * {
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.no-results {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  color: rgba(255, 255, 255, 0.8);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shortcuts-grid {
    grid-template-columns: repeat(auto-fill, minmax(85px, 1fr));
    gap: 12px;
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .shortcuts-grid {
    grid-template-columns: repeat(auto-fill, minmax(75px, 1fr));
    gap: 10px;
    padding: 12px;
  }
}
</style>